#include "shortcutconfigdialog.h"
#include "ui_shortcutconfigdialog.h"
#include <QKeySequenceEdit>
#include <QPushButton>

ShortcutConfigDialog::ShortcutConfigDialog(const QHash<QString, QAction*>& actions, QWidget *parent)
    : QDialog(parent), ui(new Ui::ShortcutConfigDialog) {
    ui->setupUi(this);

    // 连接标准按钮信号
    connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
    connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
    // 初始化表格
    ui->shortcutTable->setRowCount(actions.size());
    int row = 0;

    // 添加重置按钮
    QPushButton *resetButton = ui->buttonBox->addButton("恢复默认", QDialogButtonBox::ResetRole);
    connect(resetButton, &QPushButton::clicked, this, &ShortcutConfigDialog::onResetToDefaults);

    // 填充表格
    for (auto it = actions.begin(); it != actions.end(); ++it) {
        QTableWidgetItem *actionItem = new QTableWidgetItem(it.value()->text());
        actionItem->setFlags(actionItem->flags() ^ Qt::ItemIsEditable);

        QKeySequenceEdit *keyEdit = new QKeySequenceEdit(it.value()->shortcut());
        keyEdit->setProperty("actionId", it.key());

        ui->shortcutTable->setItem(row, 0, actionItem);
        ui->shortcutTable->setCellWidget(row, 1, keyEdit);
        defaultShortcuts[it.key()] = it.value()->shortcut();
        row++;
    }

    ui->shortcutTable->resizeColumnsToContents();
}

ShortcutConfigDialog::~ShortcutConfigDialog() {
    delete ui;
}

QHash<QString, QKeySequence> ShortcutConfigDialog::getShortcuts() const {
    QHash<QString, QKeySequence> shortcuts;

    for (int i = 0; i < ui->shortcutTable->rowCount(); ++i) {
        QKeySequenceEdit *edit = qobject_cast<QKeySequenceEdit*>(
            ui->shortcutTable->cellWidget(i, 1));
        QString id = edit->property("actionId").toString();
        shortcuts[id] = edit->keySequence();
    }

    return shortcuts;
}

void ShortcutConfigDialog::onResetToDefaults() {
    for (int i = 0; i < ui->shortcutTable->rowCount(); ++i) {
        QKeySequenceEdit *edit = qobject_cast<QKeySequenceEdit*>(
            ui->shortcutTable->cellWidget(i, 1));
        QString id = edit->property("actionId").toString();
        edit->setKeySequence(defaultShortcuts.value(id));
    }
}
